/**
 * 
 */
package ca.uwindsor.cs.deepweb.utility;

import java.io.File;
import java.util.Set;
import java.util.TreeSet;

/**
 * @author Liang Jie
 * 
 */
public class FileClassifier {

	/**
	 * Instance of buffered reader to read the files
	 */
	// protected BufferedReader bufferedreader_in;
	/**
	 * The directory which contains the files to be checked
	 */
	protected File dataDir;

	protected int offset;

	protected int quality;

	protected long length;

	protected Set<String> extensions;

	public FileClassifier(String dirpath) {
		quality = 0;
		offset = 1;
		dataDir = new File(dirpath);
		extensions = new TreeSet<String>();
	}

	public void addExtension(String extension) {
		extensions.add(extension);
	}

	public void classify(long len) {
		// File[] dataFiles = dataDir.listFiles();
		System.out.println("Start to process the files!");
		// for (int i = 0; i < dataFiles.length; i++) {
		// File file = dataFiles[i];
		// if (file.isFile() && file.getName().endsWith(".txt") && file.length()
		// < length) {
		// System.out.println(file.getName());
		// quality ++;
		// }
		// }
		length = len;
		classify(dataDir);
		System.out.println("Quality: " + quality);
	}

	protected void classify(File dir) {
		File[] dataFiles = dir.listFiles();
		// System.out.println("Start to process the files!");
		for (int i = 0; i < dataFiles.length; i++) {
			File file = dataFiles[i];
			// if(){
			if (file.isFile()) {
				// String[] temp = file.getName().split(".");
				// String extension = temp[temp.length - 1];
				String extension ;
				int j = file.getName().lastIndexOf('.');

				if ((j > 0) && (i < (file.getName().length() - 1))) {
					extension = file.getName().substring(j + 1);

					if (extensions.contains(extension)
							&& file.length() < length) {
						System.out.println(file.getAbsolutePath());
						quality++;
					}
				}
			} else if (file.isDirectory()) {
				classify(file);
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		args = new String[3];
		args[0] = "D:\\test";
		args[1] = Integer.toString(1024);
		args[2] = "txt,htm,html,xml";

		FileClassifier fc = new FileClassifier(args[0]);
		String[] extensions = args[2].split(",");
		for (int index = 0; index < extensions.length; index++) {
			fc.addExtension(extensions[index]);
		}
		fc.classify(Long.parseLong(args[1]));
	}

}
